import { Injectable } from '@nestjs/common';
import { CreateEmployeeDto } from './dto/create-employee.dto';
import { UpdateEmployeeDto } from './dto/update-employee.dto';
import { Repository } from 'typeorm';
import { Employee } from './entities/employee.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Result } from '../common/dto/common.result';
import { PageEmployeeDto } from './dto/page-employee.dto';
import { PageResult } from '../common/dto/common.page-result';

@Injectable()
export class EmployeeService {
  constructor(
    @InjectRepository(Employee)
    private readonly employeeRepository: Repository<Employee>,
  ) { }

  async create(createEmployeeDto: CreateEmployeeDto) {
    await this.employeeRepository.save(createEmployeeDto);
  }

  async findAll() {
    return await this.employeeRepository.find();
  }

  async findOne(id: number) {
    return await this.employeeRepository.findOne({ where: { id } });
  }

  async update(id: number, updateEmployeeDto: UpdateEmployeeDto) {
    await this.employeeRepository.update(id, updateEmployeeDto);
  }

  async remove(id: number) {
    const employee = await this.employeeRepository.findOne({ where: { id } });
    if (employee) {
      this.employeeRepository.remove(employee);
    } else {
      throw new Error('员工信息不存在');
    }
  }

  async page(pageEmployeeDto: PageEmployeeDto) {
    const { page, size, name, mobile, teach, status, roleId } = pageEmployeeDto;
    const query = this.employeeRepository.createQueryBuilder('employee');
    if (name) {
      query.andWhere('employee.name like :name', { name: `%${name}%` });
    }
    if (mobile) {
      query.andWhere('employee.mobile like :mobile', { mobile: `%${mobile}%` });
    }
    if (teach) {
      query.andWhere('employee.teach = :teach', { teach });
    }
    if (status) {
      query.andWhere('employee.status = :status', { status });
    }
    if (roleId) {
      query.andWhere('employee.roleId = :roleId', { roleId });
    }

    const [list, total] = await query
      .skip((page - 1) * size)
      .take(size)
      .getManyAndCount();

    return new PageResult(page, size, total, list);
  }
}
